﻿using Furion.DependencyInjection;
using GWB.Application.System.OrgManage.Dtos;
using GWB.Core;
using GWB.Supplier;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GWB.Application.System.OrgManage.OrgService
{
    /// <summary>
    /// 组织管理
    /// </summary>
    public class OrgService : SqlSugarDb, ITransient, IOrgService
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<Result<OrgOutDto>> Add(OrgCreateOrUpdateInputDto inputDto)
        {
            var result = new Result<OrgOutDto>();
            var org = await OrgDal.GetFirstAsync(x => x.Id == inputDto.ParentId);
            var createData = inputDto.Adapt<GWB.Core.TableEntity.Org>();
            createData.ParentChain = org == null ? "" : $"{org.ParentChain}>{inputDto.ParentId}";
            var data = await OrgDal.Create(createData);
            result.Data = data.Adapt<OrgOutDto>();
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> Delete(List<long> ids)
        {
            return await OrgDal.Delete(ids);
        }

        /// <summary>
        /// 获取组织树
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrgTreeOutDto>> GetOrgTree()
        {
            var dataList = await OrgDal.GetListAsync();
            return await OrgTreeRecursion(dataList.Select(x => new OrgTreeOutDto()
            {
                Key = x.Id,
                Title = x.Name,
                ParentId = x.ParentId
            }).ToList(), 0);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> Update(OrgCreateOrUpdateInputDto inputDto)
        {
            var org = await OrgDal.GetFirstAsync(x => x.Id == inputDto.ParentId);
            var updateData = inputDto.Adapt<GWB.Core.TableEntity.Org>();
            updateData.ParentChain = org == null ? "" : $"{org.ParentChain}>{inputDto.ParentId}";
            return await OrgDal.Update(updateData);
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="dataList"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        private async Task<List<OrgTreeOutDto>> OrgTreeRecursion(List<OrgTreeOutDto> dataList, long pId)
        {
            var list = dataList.Where(x => x.ParentId == pId).ToList();
            foreach (var item in list)
            {
                item.Children = await OrgTreeRecursion(dataList, item.Key);
            }
            return list;
        }

    }
}
